use anyhow::Ok;
use anyhow::Result;
use std::fs;
use std::io::prelude::*;
use std::io::BufReader;

#[allow(dead_code)]
fn log_create(path: &str) -> Result<fs::File> {
    let fp = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(path)?;
    // 设置mode 只在linux 下使用
    // use std::os::unix::fs::OpenOptionsExt;
    // fp.set_mode(0o666);
    // fp 不用显式关闭，超出作用域回自动销毁
    Ok(fp)
}
#[allow(dead_code)]
fn log_append(mut fp: &fs::File, line: &str) -> Result<()> {
    let mut buf = line.as_bytes().to_vec();
    buf.extend_from_slice("\n".as_bytes());
    fp.write(buf.by_ref())?;
    fp.sync_all()?; // fsync
    Ok(())
}
#[allow(dead_code)]
fn log_read(fp: &fs::File) -> Result<Vec<String>> {
    let mut logs = vec![];
    let scanner = BufReader::new(fp);
    for line in scanner.lines() {
        let line = line?;
        logs.push(line);
        
    }
    Ok(logs)
}

#[cfg(test)]
mod tests {
    // 导入上级模块
    use super::*;
    #[test]
    fn test_logs() {
        let path="d:/a.log";
        let mut fp = log_create(path).unwrap();
        log_append(&fp, "aaa").unwrap();
        log_append(&fp, "bbb").unwrap();
        
        //注意这里需要反转文件
        fp.rewind().unwrap();
        let lines = log_read(&fp).unwrap();
        fs::remove_file(path).unwrap();
        assert_eq!(vec!["aaa","bbb"], lines);
    }
}
